package com.xu.demo.feature.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONReader;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ReadJsonFileUtil {

    /**
     * 读取 json 文件, 以流的形式读取, 避免文本超长报错
     * @param filePath filePath
     * @return JSONArray
     */
    public static JSONArray readJson2Arr(String filePath)  {
        JSONArray arr = new JSONArray();
        try {// 初始化资源
            Resource resource = new ClassPathResource(filePath);
            @Cleanup InputStream inputStream = resource.getInputStream();
            @Cleanup Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            @Cleanup BufferedReader br = new BufferedReader(reader);
            @Cleanup JSONReader jr = new JSONReader(br);

            // 读取 json arr
            jr.startArray();
            while(jr.hasNext()){
                JSONArray value = (JSONArray) jr.readObject();
                arr.addAll(value);
            }
            jr.endArray();
            jr.close();
        } catch (IOException e) {// IO异常 返回空数组
            log.error("exception message", e);
            return new JSONArray();
        }
        return arr;
    }

    /**
     * 读取 json 文件, 以流的形式读取, 避免文本超长报错
     * @param filePath filePath
     * @return JSONArray
     */
    public static List<JSONObject> readJson2List(String filePath)  {
        List<JSONObject> arr = new ArrayList<>();
        try {// 初始化资源
            Resource resource = new ClassPathResource(filePath);
            @Cleanup InputStream inputStream = resource.getInputStream();
            @Cleanup Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            @Cleanup BufferedReader br = new BufferedReader(reader);
            @Cleanup JSONReader jr = new JSONReader(br);

            // 读取 json arr
            jr.startArray();
            while(jr.hasNext()){
                JSONArray value = (JSONArray) jr.readObject();
                if(value == null) return arr;// 快速返回

                for (int i = 0; i < value.size(); i++) arr.add(value.getJSONObject(i));
            }
            jr.endArray();
            jr.close();
        } catch (IOException e) {// IO异常 返回空数组
            log.error("exception message", e);
            return new ArrayList<>();
        }
        return arr;
    }
}
